package nginxdeploylogic

import (
	"context"
	"errors"
	"fmt"
	"github.com/zeromicro/go-zero/core/logx"
	"os"
	"strings"
	"sync"
	"time"
	"yunzhan/common/models"
	utils "yunzhan/common/utils"
	"yunzhan/rpc-server/internal/svc"
	agent "yunzhan/rpc-server/pb"
)

type DeployNginxLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewDeployNginxLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DeployNginxLogic {
	return &DeployNginxLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// DeployNginx 部署Nginx
func (l *DeployNginxLogic) DeployNginx(in *agent.DeployNginxRequest) (*agent.DeployResponse, error) {
	if in.NodeInfo == nil {
		return &agent.DeployResponse{
			Code:    500,
			Message: "未配置节点信息, 无法执行Nginx部署",
		}, errors.New("未配置节点信息, 无法执行Nginx部署")
	}

	resp := &agent.DeployResponse{
		Code:    200,
		Message: fmt.Sprintf("请求已接收，正在部署 %s 到节点 %s", in.ConfigInfo.ComponentName, in.NodeInfo.Host),
	}

	go l.startDeployment(in)

	return resp, nil
}

func (l *DeployNginxLogic) startDeployment(in *agent.DeployNginxRequest) {

	var wg sync.WaitGroup

	wg.Add(1)
	go func() {
		defer wg.Done()

		// 创建 LogManager 实例
		logManager := models.NewLogManager(100, fmt.Sprintf("http://%s:%d", l.svcCtx.Config.RestServices["apiServer"].RestConf.Host, l.svcCtx.Config.RestServices["apiServer"].RestConf.Port))
		defer logManager.Close()

		flushInterval := 5 * time.Second // 刷新间隔
		maxBatchSize := 100              // 最大批量大小
		retryDelay := 2 * time.Second    // 重试延迟
		maxRetries := 3                  // 最大重试次数

		// 创建 ComponentInfoManager 实例
		componentInfoManager := models.NewComponentInfoManager(
			1000,
			fmt.Sprintf("http://%s:%d", l.svcCtx.Config.RestServices["apiServer"].RestConf.Host, l.svcCtx.Config.RestServices["apiServer"].RestConf.Port),
			flushInterval,
			maxBatchSize,
			retryDelay,
			maxRetries)
		defer componentInfoManager.Close()

		packageDirectory := in.ConfigInfo.PackagePath
		rtrimDir := utils.Rtrim(packageDirectory, "/")
		logx.Infof("安装包存放目录: %s", rtrimDir)
		nginxVersion := in.ConfigInfo.ComponentName
		baseInfo := fmt.Sprintf("安装包存放目录: %s, Nginx version: %s, Nginx安装目录: %s", rtrimDir, nginxVersion, "/usr/local/nginx")
		step := 1
		logManager.SendLog(in.ClusterID, in.NodeInfo.Host, step, "INFO", baseInfo, "Nginx", "Server")

		step++
		logManager.SendLog(in.ClusterID, in.NodeInfo.Host, step, "INFO", "解压安装包...", "Nginx", "Server")
		tarCommand := fmt.Sprintf("sudo tar -xzf %s/%s -C /usr/local", rtrimDir, nginxVersion)
		output, err := utils.ExecCommand(tarCommand)
		if err != nil {
			message := fmt.Sprintf("解压安装包异常: %v, output: %s", err, output)
			logManager.SendLog(in.ClusterID, in.NodeInfo.Host, step, "ERROR", message, "Nginx", "Server")
			return
		}
		logManager.SendLog(in.ClusterID, in.NodeInfo.Host, step, "INFO", "解压安装包成功", "Nginx", "Server")
		step++
		logManager.SendLog(in.ClusterID, in.NodeInfo.Host, step, "INFO", "配置nginx.conf文件...", "Nginx", "Server")

		file, err := os.Create("/usr/local/nginx/conf/nginx.conf")
		if err != nil {
			message := fmt.Sprintf("failed to create or open file: %v", err)
			logManager.SendLog(in.ClusterID, in.NodeInfo.Host, step, "ERROR", message, "Nginx", "Server")
			return
		}
		defer file.Close()

		_, err = file.WriteString(in.NginxConfig.Content)
		if err != nil {
			message := fmt.Sprintf("failed to write string to file: %v", err)
			logManager.SendLog(in.ClusterID, in.NodeInfo.Host, step, "ERROR", message, "Nginx", "Server")
			return
		}

		err = file.Sync()
		if err != nil {
			message := fmt.Sprintf("failed to sync file content: %v", err)
			logManager.SendLog(in.ClusterID, in.NodeInfo.Host, step, "ERROR", message, "Nginx", "Server")
			return
		}
		step++
		logManager.SendLog(in.ClusterID, in.NodeInfo.Host, step, "INFO", "配置nginx.conf文件完成", "Nginx", "Server")

		serviceFile := fmt.Sprintf(`[Unit]
Description=/usr/local/nginx/sbin/nginx Compatibility
ConditionFileIsExecutable=/usr/local/nginx/sbin/nginx
After=network.target

[Service]
Type=forking
PrivateTmp=true
ExecStartPre=/usr/local/nginx/sbin/nginx -t
ExecStart=/usr/local/nginx/sbin/nginx
ExecReload=/usr/local/nginx/sbin/nginx -s reload
ExecStop=/usr/local/nginx/sbin/nginx -s stop

TimeoutSec=0
RemainAfterExit=yes
Restart=on-failure
RestartSec=5

[Install]
WantedBy=multi-user.target`)

		step++
		logManager.SendLog(in.ClusterID, in.NodeInfo.Host, step, "INFO", "创建nginx.service文件...", "Nginx", "Server")
		writeServiceFileCommand := fmt.Sprintf("echo '%s' | sudo tee /etc/systemd/system/nginx.service", serviceFile)
		output, err = utils.ExecCommand(writeServiceFileCommand)
		if err != nil {
			message := fmt.Sprintf("创建 nginx.service 文件异常: %v, output: %s", err, output)
			logManager.SendLog(in.ClusterID, in.NodeInfo.Host, step, "ERROR", message, "Nginx", "Server")
			return
		}
		logManager.SendLog(in.ClusterID, in.NodeInfo.Host, step, "INFO", "创建nginx.service文件完成", "Nginx", "Server")

		step++
		logManager.SendLog(in.ClusterID, in.NodeInfo.Host, step, "INFO", "启动Nginx服务...", "Nginx", "Server")
		reloadSystemdCommand := fmt.Sprintf("sudo systemctl daemon-reload && sudo systemctl enable nginx.service --now")
		output, err = utils.ExecCommand(reloadSystemdCommand)
		if err != nil {
			message := fmt.Sprintf("启动Nginx服务异常: %v, output: %s", err, output)
			logManager.SendLog(in.ClusterID, in.NodeInfo.Host, step, "ERROR", message, "Nginx", "Server")
			return
		}
		logManager.SendLog(in.ClusterID, in.NodeInfo.Host, step, "INFO", "启动Nginx服务完成", "Nginx", "Server")

		logManager.SendLog(in.ClusterID, in.NodeInfo.Host, step, "INFO", "等待Nginx服务完全启动", "Nginx", "Server")

		time.Sleep(3 * time.Second)
		step++
		statusCommand := "sudo systemctl is-active nginx.service"
		output, err = utils.ExecCommand(statusCommand)
		if err != nil || strings.TrimSpace(output) != "active" {
			message := fmt.Sprintf("Nginx启动后未正常运行: %v, output: %s", err, output)
			logManager.SendLog(in.ClusterID, in.NodeInfo.Host, step, "ERROR", message, "Nginx", "Server")
			return
		}
		logManager.SendLog(in.ClusterID, in.NodeInfo.Host, step, "INFO", "Nginx部署成功", "Nginx", "Server")

		currentIP, currentIPErr := utils.GetCurrentInternalIP()
		if err != nil {
			message := fmt.Sprintf("%s: 无法获取当前主机IP: %v", in.NodeInfo.Host, currentIPErr)
			logManager.SendLog(in.ClusterID, in.NodeInfo.Host, step, "ERROR", message, "Nginx", "Server")
			return
		}
		currentHost, currentHostErr := utils.GetCurrentHostname()
		if err != nil {
			message := fmt.Sprintf("%s: 无法获取当前主机名: %v", in.NodeInfo.Host, currentHostErr)
			logManager.SendLog(in.ClusterID, in.NodeInfo.Host, step, "ERROR", message, "Nginx", "Server")
			return
		}

		nginxInfo := &models.ComponentInfo{
			ClusterID:      in.ClusterID,
			ComponentName:  "Nginx",
			Version:        in.Version,
			NodeHost:       currentHost,
			NodeIP:         currentIP,
			ComponentRole:  "Server",
			HomePath:       "/usr/local/nginx",
			DataStorageDir: "",
			Port:           "80",
			Status:         true,
			AdditionalInfo: fmt.Sprintf("config_file=/usr/local/nginx/conf/nginx.conf"),
		}

		componentInfoManager.SendComponentInfo(nginxInfo)

	}()
	wg.Wait()

}
